<?php

namespace app\api\controller;

use app\api\logic\LoginLogic;
use app\api\validate\LoginValidate;
use app\api\validate\RegisterValidate;
use app\common\basic\BasicApiController;
use app\common\service\FileLockService;
use think\facade\Log;
use think\facade\Cache;
use think\facade\Db;
use think\Request;

class Login extends BasicApiController
{
    protected $loginLogic;

    public function __construct(Request $request)
    {
        $this->loginLogic = new LoginLogic();
        $this->request = $request;
    }

    public function login()
    {
        try {
            $validateResult = (new LoginValidate())->post()->goCheck();

            if (!empty($validateResult['error'])) {
                return error($validateResult['msg']);
            }

            $params = $validateResult['data'];
            $loginResult = $this->loginLogic->login($params);

            if ($loginResult['error']) {
                return error($loginResult['msg']);
            }

            return success($loginResult['data']);
        } catch (\Exception $e) {
            // 验证过程中抛出的异常
            return error($e->getMessage());
        }
    }


    public function register()
    {
        $data = $this->request->only(['username', 'password']);
        $validate = new RegisterValidate();
        if (!$validate->check($data)) {
            return_error($validate->getError(),0);
        }
        Db::startTrans();// 开启数据库事务
        try {
            $fileLock = new FileLockService(); //实例化文件锁用于控制访问
            $fileLock->lock('user/register/' . $data['username']);
            // IP 限制逻辑
            $ip = $this->request->ip();
            $ipKey = "register_count_{$ip}";
            $count = Cache::get($ipKey, 0);
            $maxAttempts = 3; // 每小时最多注册次数
            if ($count >= $maxAttempts) {
                return_error('同一 IP 在一小时内注册次数过多');
            }
            // 增加 IP 注册计数
            Cache::tag('register_ip')->set($ipKey, $count + 1, 3600); // 缓存1小时
            // 执行注册逻辑
            $result = $this->loginLogic->register($data);
            Db::commit();
            return success($result);
        } catch (\Exception $e) {
            Db::rollback();
            return_error($e->getMessage(), 0);// 抛出异常
        } finally {
            $fileLock->unlock(); // 解锁
        }
    }
}